/**
 * 用于回填表单值
 */
import moment from 'moment';
import BraftEditor from 'braft-editor';
import { stringify } from 'qs';
import { getDuration } from '@/utils/utils';
import { getLeaveUnit } from '@/pages/Flow/Mine/ApplyPage/utils';
import { Time } from '@/components/Custom/CustomDatePicker/CustomDatePicker';
import { dictionaryList } from '@/services/dictionary';
import { companysearchCandidate as searchCandidate } from '@/services/flowMine/apply';
import request from '@/utils/request';
import clone from 'lodash/clone';
import { getEmployeeInfoList } from '@/services/components/userform';
import FORM_TYPE_MAP from './consts';

const getDayType = (value, country, type) => {
    if (!value) return '';
    if (Time[country].am[type] === moment(value).format('HH:mm')) {
        return 'am';
    }
    if (Time[country].pm[type] === moment(value).format('HH:mm')) {
        return 'pm';
    }
    return '';
};

const renderAttachment = (form, valueJson, name = 'workflowFile', fieldName = 'attachment') => {
    // 附件
    const fileList = [];
    const files =
        (valueJson.offerFile && valueJson.offerFile.length > 0 && valueJson.offerFile) || valueJson[name] || [];
    if (files.length === 0) return;
    files.forEach(item => {
        const { originName, url, keyName } = item;
        const fileObj = {
            keyName,
            name: originName,
            url,
            uid: keyName
        };
        fileList.push(fileObj);
    });
    form.setFieldsValue({
        [fieldName]: {
            allFileList: fileList,
            uploadResourceFile: null
        }
    });
};

const fillForm = ({
    query,
    form,
    currentUser,
    country,
    formType,
    valueJson,
    leaveTypeList,
    postType,
    reason1,
    setDuration,
    setLevelType,
    setReason2,
    setTakeUsers,
    setPostList,
    setLeaders,
    setRecorder,
    setPageLoading,
    setFetching,
    setOriginInstitutionName
}) => {
    const { formValueJson } = valueJson;
    const { leaveType, formatTime = 3 } = formValueJson;

    setTimeout(() => {
        Object.keys(formValueJson).forEach((prop, index) => {
            const value = formValueJson[prop];
            if (prop === 'startTime') {
                form.setFieldsValue({
                    startTime: {
                        ...form.getFieldValue(prop),
                        // 规则制度时间精确到天，其他按 formTime 字段来，默认 3
                        unit:
                            formType === FORM_TYPE_MAP.TYPE_ON_SYSTEM
                                ? 1
                                : getLeaveUnit(leaveTypeList, leaveType) || formatTime || 3,
                        disabled: false,
                        time: value ? moment(value) : null,
                        dayType: getDayType(value, country, prop),
                        timeValue: formatTime === 3 && value ? moment(value).format('HH:mm') : ''
                    }
                });

                // ---------------------------------------------------------- 职级逻辑开始
                // 职级生效日期特殊处理：
                const specialTypes = [
                    FORM_TYPE_MAP.ADD_GRADE_TYPE,
                    FORM_TYPE_MAP.ADD_GRADE,
                    FORM_TYPE_MAP.EDIT_GRADE,
                    FORM_TYPE_MAP.EDIT_GRADE_TYPE,
                    FORM_TYPE_MAP.REMOVE_GRADE,
                    FORM_TYPE_MAP.REMOVE_GRADE_TYPE
                ];
                if (specialTypes.includes(formType)) {
                    form.setFieldsValue({
                        startTime: {
                            ...form.getFieldValue(prop),
                            unit: 4
                        }
                    });
                }
                // ---------------------------------------------------------- 职级逻辑结束
            } else if (prop === 'endTime') {
                form.setFieldsValue({
                    endTime: {
                        ...form.getFieldValue('endTime'),
                        disabled: false,
                        unit:
                            formType === FORM_TYPE_MAP.TYPE_ON_SYSTEM
                                ? 1
                                : getLeaveUnit(leaveTypeList, leaveType) || formatTime || 3,
                        time: value ? moment(value) : null,
                        dayType: getDayType(value, country, 'endTime'),
                        timeValue: formatTime === 3 && value ? moment(value).format('HH:mm') : ''
                    }
                });
            } else if (prop === 'releaseTime') {
                form.setFieldsValue({
                    [prop]: {
                        ...form.getFieldValue(prop),
                        time: value ? moment(value) : null
                    }
                });
            } else if (prop === 'returnToWork') {
                form.setFieldsValue({
                    returnToWork: {
                        ...form.getFieldValue('endTime'),
                        time: value ? moment(value) : null,
                        unit: 1
                    }
                });
            } else if (['entryDate', 'entryDateEnd', 'talentBirth', 'contractBeginDate'].includes(prop)) {
                form.setFieldsValue({
                    [prop]: {
                        ...form.getFieldValue(prop),
                        time: value ? moment(value) : null,
                        unit: 1
                    }
                });
            } else if (prop === 'duration') {
                form.setFieldsValue({
                    duration: getDuration(value, getLeaveUnit(leaveTypeList, leaveType) || formatTime || 3)
                });
                setDuration(value);
            } else if (['attachment', 'attachmentNews', 'attachmentRec', 'institutionAttachment'].includes(prop)) {
                // do noting
            } else if (prop === 'labelCn' || prop === 'labelEn') {
                form.setFieldsValue({
                    [prop]: value || []
                });
            } else if (prop === 'demandCompanyId') {
                form.setFieldsValue({
                    [prop]: formValueJson.demandCompanyIdName || ''
                });
            } else if (prop === 'postType') {
                form.setFieldsValue({
                    [prop]: value
                });
                const find = postType.find(item => item.dictValue === `${value}`);
                if (find) {
                    dictionaryList({
                        code: find.remark
                    }).then(result => {
                        if (result.code === 10000) {
                            setLevelType(result.data);
                        }
                    });
                }
            } else if (prop === 'reason1') {
                form.setFieldsValue({
                    [prop]: value
                });
                const find = reason1.find(item => item.dictValue === `${value}`);
                if (find) {
                    dictionaryList({
                        code: find.remark
                    }).then(result => {
                        if (result.code === 10000) {
                            setReason2(result.data);
                        }
                    });
                }
            } else if (prop === 'talentName') {
                if (formValueJson.talentNameName) {
                    searchCandidate({
                        candidateName: formValueJson.talentNameName,
                        companyId: currentUser.companyId,
                        searchStage: 'offer'
                    }).then(response => {
                        if (response.code === 10000) {
                            setTakeUsers(response.data);
                            form.setFieldsValue({
                                [prop]: value
                            });
                        }
                    });
                }
            } else if (prop === 'teacherId') {
                if (value) {
                    request('/api/oa/v1/employee/getservicepersonlist', {
                        method: 'POST',
                        data: {
                            companyId: currentUser.companyId,
                            userName: formValueJson[`${prop}Name`]
                        }
                    }).then(response => {
                        if (response.code === 10000) {
                            setLeaders(response.data);
                            form.setFieldsValue({
                                [prop]: value
                            });
                        }
                    });
                }
            } else if (prop === 'backRecorderId') {
                if (value) {
                    getEmployeeInfoList({
                        companyId: currentUser.companyId,
                        userName: formValueJson[`${prop}Name`]
                    }).then(response => {
                        if (response.code === 10000) {
                            setRecorder(response.data.map(item => ({ ...item, userCode: item.employeeCode })));
                            form.setFieldsValue({
                                [prop]: value
                            });
                        }
                    });
                }
            } else if (prop === 'originInstitutionId') {
                if (value) {
                    console.log('有进入value', value);
                    setFetching(true);
                    request(
                        `/api/oa/v1/institutions/origin?${stringify({
                            institutionType: form.getFieldValue('institutionType'),
                            companyId: currentUser.companyId
                        })}`,
                        {
                            method: 'GET'
                        }
                    ).then(response => {
                        if (response.code === 10000) {
                            setFetching(false);
                            setOriginInstitutionName(response.data);
                            form.setFieldsValue({
                                [prop]: value
                            });
                        }
                    });
                    // }
                } else {
                    setOriginInstitutionName([]);
                }
            } else if (prop === 'newsCnContent' || prop === 'newsEnContent') {
                form.setFieldsValue({
                    [prop]: BraftEditor.createEditorState(value)
                });
            } else if (prop === 'applyDate' && !query.reedid) {
                form.setFieldsValue({
                    [prop]: moment().format('YYYY-MM-DD')
                });
            } else if (prop === 'entryPost' || prop === 'recruitPost') {
                if (value) {
                    request('/api/oa/v1/post/getpostlistbycondition', {
                        method: 'POST',
                        data: {
                            departmentId:
                                (formValueJson &&
                                    formValueJson.demandDepartmentId &&
                                    clone(formValueJson.demandDepartmentId).pop()) ||
                                ''
                            // companyId: currentUser.companyId,
                            // postName: formValueJson[`${prop}Name`]
                        }
                    }).then(response => {
                        if (response.code === 10000) {
                            const newDate = response.data.map(item => ({
                                ...item,
                                id: String(item.id)
                            }));
                            setPostList(newDate);
                            form.setFieldsValue({
                                [prop]: String(value)
                            });
                        }
                    });
                }
            } else {
                form.setFieldsValue({
                    [prop]: value
                });
            }
            if (index === Object.keys(formValueJson).length - 1) {
                setPageLoading(false);
            }
        });
        renderAttachment(form, valueJson);
        renderAttachment(form, valueJson, 'officeFile', 'attachmentNews');
        renderAttachment(form, valueJson, 'officeResFile', 'attachmentRec');
        renderAttachment(form, valueJson, 'institutionFile', 'institutionAttachment');
    }, 0);
};

export default fillForm;
